/*
 * Copyright (C) 2025 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package top.xbaistack.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Simple JSON mapping processing tool
 *
 * @author xbaistack
 * @since 2025/03/25
 */
@Slf4j
@Component
@DependsOn("jacksonObjectMapper")
public final class JsonMapper implements DisposableBean {

    private static ObjectMapper mapper;
    private static final Object LOCK = new Object();

    public JsonMapper(ObjectProvider<ObjectMapper> provider) {
        ObjectMapper om = provider.getIfAvailable();
        JsonMapper.mapper = om.copy();
        JsonMapper.mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    public static ObjectMapper mapper() {
        synchronized (LOCK) {
            if (mapper == null) {
                synchronized (LOCK) {
                    mapper = new ObjectMapper(); // Default
                }
            }
        }
        return mapper;
    }

    public static <T> T fromJson(String content, Class<T> valueType) {
        if (StringUtils.isNotBlank(content)) {
            try {
                return mapper().readValue(content, valueType);
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public static <T> T fromJson(String content, TypeReference<T> typeReference) {
        if (StringUtils.isNotBlank(content)) {
            try {
                return mapper().readValue(content, typeReference);
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public static String toJSONString(Object source) {
        try {
            return mapper().writeValueAsString(source);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
            return "N/A";
        }
    }

    public static String toJSONPString(String function, Object source) {
        if (source == null) {
            return String.format("%s()", function);
        }
        return toJSONString(new JSONPObject(function, source));
    }

    @Override
    public void destroy() throws Exception {
        JsonMapper.mapper = null;
    }

}
